<template>
  <el-dialog
    title="用户注册"
    :visible.sync="dialogVisible"
    width="600px"
    center
  >
    <el-form
      :model="form"
      ref="form"
      :rules="rules"
      label-width="80px"
      :inline="false"
      size="normal"
    >
      <el-form-item label="头像" prop="avatar">
        <el-upload
          class="avatar-uploader"
          :action="uploadUrl"
          :show-file-list="false"
          :data="uploadObj"
          :on-success="handleAvatarSuccess"
          :before-upload="beforeAvatarUpload"
        >
          <img v-if="imageUrl" :src="imageUrl" class="avatar" />
          <i v-else class="el-icon-plus avatar-uploader-icon"></i>
        </el-upload>
      </el-form-item>
      <el-form-item label="昵称" prop="username">
        <el-input v-model="form.username"></el-input>
      </el-form-item>
      <el-form-item label="邮箱" prop="email">
        <el-input v-model="form.email"></el-input>
      </el-form-item>
      <el-form-item label="手机" prop="phone">
        <el-input v-model="form.phone"></el-input>
      </el-form-item>
      <el-form-item label="密码" prop="password">
        <el-input v-model="form.password"></el-input>
      </el-form-item>
      <el-row>
        <el-col :span="16">
          <el-form-item label="图形码" prop="code">
            <el-input v-model="form.code"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="7">
          <img
            :src="rcodePic"
            alt=""
            style="margin-left:5px"
            @click="rcodeClick"
          />
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="16">
          <el-form-item label="验证码" prop="rcode">
            <el-input v-model="form.rcode"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="7">
          <el-button style="margin-left:20px" @click="getUserCode"
            >获取用户验证码</el-button
          >
        </el-col>
      </el-row>
    </el-form>

    <span slot="footer" class="dialog-footer">
      <el-button @click="dialogVisible = false">取 消</el-button>
      <el-button type="primary" @click="submit">确 定</el-button>
    </span>
  </el-dialog>
</template>
<script>
export default {
  name: 'UserRegist',
  data () {
    return {
      rcodePic: process.env.VUE_APP_BASEURL + '/captcha?type=sendsms',
      dialogVisible: false,
      imageUrl: '',
      uploadObj: {},
      uploadUrl: process.env.VUE_APP_BASEURL + '/uploads',
      form: {
        username: '',
        phone: '',
        email: '',
        avatar: '',
        password: '',
        rcode: '',
        code: ''
      },
      rules: {
        username: [{ required: true, message: '请输入昵称', trigger: 'blur' }],
        phone: [
          {
            required: true,
            validator: (rule, value, callback) => {
              if (!value) {
                return callback(new Error('请输入手机号码'))
              }
              const reg = /^1[3-9][0-9]{9}$/
              if (!reg.test(value)) {
                return callback(new Error('请输入合法的手机号码'))
              }
              callback()
            },
            trigger: 'blur'
          }
        ],
        email: [
          {
            required: true,
            validator: (rule, value, callback) => {
              if (!value) {
                return callback(new Error('请输入邮箱'))
              }
              const reg = /^[A-Za-z\d]+([-_.][A-Za-z\d]+)*@([A-Za-z\d]+[-.])+[A-Za-z\d]{2,4}$/
              if (!reg.test(value)) {
                return callback(new Error('请输入正确格式的邮箱地址'))
              }
              callback()
            },
            trigger: 'blur'
          }
        ],
        password: [{ required: true, message: '请输入密码', trigger: 'blur' }],
        code: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          { min: 4, max: 4, message: '请输入四位有效数字', trigger: 'blur' }
        ],
        rcode: [{ required: true, message: '请输入密码', trigger: 'blur' }],
        avatar: [{ required: true, message: '请上传头像', trigger: 'change' }]
      }
    }
  },
  methods: {
    submit () {
      this.$refs.form.validate(async valid => {
        if (!valid) return
        const res = await this.$axios.post('/register', this.form)
        if (res.data.code === 200) {
          this.$message({
            type: 'success',
            message: '恭喜你,注册成功',
            duration: 1000
          })
          this.$refs.form.resetFields()
          this.dialogVisible = false
        }
      })
    },
    rcodeClick () {
      this.rcodePic =
        process.env.VUE_APP_BASEURL + '/captcha?type=sendsms&sb=' + Date.now()
    },
    async getUserCode () {
      let num = 0
      this.$refs.form.validateField(['phone', 'code'], errorMessage => {
        if (!errorMessage) {
          num++
        }
      })
      if (num === 2) {
        // console.log(123)
        const res = await this.$axios.post('/sendsms', {
          phone: this.form.phone,
          code: this.form.code
        })
        if (res.data.code === 200) {
          this.form.rcode = res.data.data.captcha
        }
      }
    },
    handleAvatarSuccess (res, file) {
      if (res.code === 200) {
        this.imageUrl = URL.createObjectURL(file.raw)
        this.form.avatar = res.data.file_path
      } else {
        this.$message({
          type: 'error',
          message: '头像上传失败,请重新上传',
          duration: 1000
        })
      }
    },
    beforeAvatarUpload (file) {
      const isImage =
        file.type === 'image/jpeg' ||
        file.type === 'image/png' ||
        file.type === 'image/gif'
      const isLt2M = file.size / 1024 / 1024 < 2

      if (!isImage) {
        this.$message.error('上传头像图片只能是 JPG|PNG|GIF 格式!')
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!')
      }
      this.uploadObj.image = file
      return isImage && isLt2M
    }
  }
}
</script>
<style scope>
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>
